package com.acvoli.shopping.service;

import com.acvoli.shopping.base.entity.Order;
import com.acvoli.shopping.base.entity.OrderItem;
import com.acvoli.shopping.base.entity.ProductSku;
import com.acvoli.shopping.base.entity.SkuStock;
import com.acvoli.shopping.base.mapper.MemberMapper;
import com.acvoli.shopping.base.mapper.OrderItemMapper;
import com.acvoli.shopping.base.mapper.OrderMapper;
import com.acvoli.shopping.base.mapper.ProductMapper;
import com.acvoli.shopping.base.mapper.ProductSkuMapper;
import com.acvoli.shopping.base.mapper.SkuStockMapper;
import com.acvoli.shopping.dto.CommitOrderResponse;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    MemberMapper memberMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    ProductSkuMapper productSkuMapper;
    @Autowired
    SkuStockMapper stockMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;

    public static String getLast4MemberId(String memberId) {
        return memberId.substring(memberId.length() - 5);
    }

    @Override
    @Transactional
    public CommitOrderResponse commitNormalOrder(String memberId, String skuId, int sum) {

        for (int i = 0; i < 10; i++) {
            //查询未使用
            memberMapper.selectById(memberId);
            ProductSku sku = productSkuMapper.selectById(skuId);
            //查询未使用
            productMapper.selectById(skuId);

            //用SKU ID获取库存，如果数据有多个只要第一个
            List<SkuStock> stocks = stockMapper.selectBySkuId(skuId);
            SkuStock stock;
            if (stocks != null && stocks.size() > 0) {
                stock = stocks.get(0);
            } else {
                throw new RuntimeException();
            }

            //判断库存是否满足
            if (stock.getStock() < sum) {
                throw new RuntimeException();
            }

            //扣减库存,有锁的问题，使用乐观锁也会导致数据错误
            //同一个商品，使用乐观锁，也是串行的
            //实际情况，先扣减内存库存，再扣减数据库（行级锁），单个商品TPS是固定的，受限与数据库TPS
            //1：购买不是同一个SKU
            //2：购买同一个（）
            //3：只受用内存库存（Redis）
//            stock.setStock(stock.getStock() - sum);
//            stockMapper.updateById(stock);

            Order order = new Order();
            String orderSN = System.currentTimeMillis() + getLast4MemberId(memberId);
            order.setMemberId(Long.valueOf(memberId));
            order.setOrderSn(orderSN);
            order.setReceiverName(UUID.randomUUID().toString());
            order.setReceiverPhone("18201337072");
            order.setTotalAmount(new BigDecimal(sum * 10));
            order.setPayAmount(order.getTotalAmount());
            orderMapper.insert(order);

            OrderItem orderItem = new OrderItem();
            orderItem.setOrderSn(orderSN);
            orderItem.setOrderId(order.getId());//可能获取不到
            orderItem.setProductId(sku.getProductId());
            orderItem.setProductSkuId(Long.valueOf(skuId));
            orderItem.setProductQuantity(sum);
            orderItem.setProductPrice(new BigDecimal(10));
            orderItemMapper.insert(orderItem);
        }

        System.out.println("order success at time: " + System.currentTimeMillis());

        return null;
    }
}
